﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.Collisions.CUiCollisionsWindow
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Markup;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui;
using Tecnomatix.Engineering.Ui.WPF;

//
namespace DnProcessSimulateCommands.Collisions
{
    public class CUiCollisionsWindow : TxWindow, IComponentConnector
    {
      private TxObjGridCtrl m_firstObjectList;
      private TxObjGridCtrl m_secondObjectList;
      private Dictionary<ITxDisplayableObject, TxColor> m_objectOriginalColors;
      private List<ITxDisplayableObject> m_objectToResetColor;
      internal WindowsFormsHost firstObjectsWindowsFormHost;
      internal WindowsFormsHost secondObjectsWindowsFormHost;
      internal System.Windows.Controls.ListBox listBoxResults;
      internal TextBlock timeTextBlock;
      private bool _contentLoaded;

      public CUiCollisionsWindow()
      {
        this.InitializeComponent();
        this.MustUseNearMiss = false;
        this.AllowedPenetration = 0.0;
        this.MustComputeDistanceIfInNearMiss = false;
        this.MustFindPenetrationRegions = false;
        this.IsCollisionQueryDefinedPair = false;
        this.NearMissDistance = 0.0;
        this.IsEntityReportLevel = false;
        this.MustStopQueryAfterFirstCollision = false;
        this.DoesUseAllowedPenetration = false;
        this.DoesUsePredefinedAllowedPairs = false;
        this.m_firstObjectList = new TxObjGridCtrl();
        this.m_secondObjectList = new TxObjGridCtrl();
        this.m_firstObjectList.ListenToPick = true;
        this.m_firstObjectList.PickLevel = (TxPickLevel) 6;
        this.m_firstObjectList.ValidatorType = (TxValidatorType) 20;
        this.m_firstObjectList.SetValidator((ITxValidator) new CUiCollisionsValidator(this.m_firstObjectList, this.m_secondObjectList));
        this.firstObjectsWindowsFormHost.Child = (System.Windows.Forms.Control) this.m_firstObjectList;
        this.firstObjectsWindowsFormHost.Focusable = true;
        this.m_firstObjectList.Picked += new TxObjGridCtrl_PickedEventHandler(this.m_firstObjectList_Picked);
        this.m_secondObjectList.ListenToPick = true;
        this.m_secondObjectList.PickLevel = (TxPickLevel) 6;
        this.m_secondObjectList.ValidatorType = (TxValidatorType) 20;
        this.m_secondObjectList.SetValidator((ITxValidator) new CUiCollisionsValidator(this.m_secondObjectList, this.m_firstObjectList));
        this.secondObjectsWindowsFormHost.Child = (System.Windows.Forms.Control) this.m_secondObjectList;
        this.secondObjectsWindowsFormHost.Focusable = true;
        this.m_secondObjectList.Picked += new TxObjGridCtrl_PickedEventHandler(this.m_secondObjectList_Picked);
        this.m_objectOriginalColors = new Dictionary<ITxDisplayableObject, TxColor>();
        this.m_objectToResetColor = new List<ITxDisplayableObject>();
      }

      private void TxWindow_Closing(object sender, CancelEventArgs e)
      {
        this.ResetObjectColors();
        this.m_firstObjectList.Picked -= new TxObjGridCtrl_PickedEventHandler(this.m_firstObjectList_Picked);
        this.m_secondObjectList.Picked -= new TxObjGridCtrl_PickedEventHandler(this.m_secondObjectList_Picked);
      }

      public void m_firstObjectList_Picked(object sender, TxObjGridCtrl_PickedEventArgs args)
      {
        ((Collection<ITxObject>) this.m_firstObjectList.Objects).Add(args.Obj);
      }

      public void m_secondObjectList_Picked(object sender, TxObjGridCtrl_PickedEventArgs args)
      {
        ((Collection<ITxObject>) this.m_secondObjectList.Objects).Add(args.Obj);
      }

      public bool MustUseNearMiss { get; set; }

      public double AllowedPenetration { get; set; }

      public bool MustComputeDistanceIfInNearMiss { get; set; }

      public bool MustFindPenetrationRegions { get; set; }

      public bool IsCollisionQueryDefinedPair { get; set; }

      public double NearMissDistance { get; set; }

      public bool IsEntityReportLevel { get; set; }

      public bool MustStopQueryAfterFirstCollision { get; set; }

      public bool DoesUseAllowedPenetration { get; set; }

      public bool DoesUsePredefinedAllowedPairs { get; set; }

      private void ComputeTestButton_Click(object sender, RoutedEventArgs e)
      {
        TxCollisionQueryParams collisionQueryParams = this.CreateCollisionQueryParams();
        TxObjectList objects1 = this.m_firstObjectList.Objects;
        TxObjectList objects2 = this.m_secondObjectList.Objects;
        TxCollisionRoot collisionRoot = TxApplication.ActiveDocument.CollisionRoot;
        Stopwatch stopwatch = Stopwatch.StartNew();
        TxCollisionQueryResults objectsFromLists = collisionRoot.GetCollidingObjectsFromLists(objects1, objects2, collisionQueryParams);
        stopwatch.Stop();
        this.DisplayResults(objectsFromLists, stopwatch.Elapsed.TotalSeconds);
      }

      private void DisplayResults(TxCollisionQueryResults results, double timeInSecond)
      {
        this.listBoxResults.Items.Clear();
        this.ResetObjectColors();
        this.timeTextBlock.Text = timeInSecond.ToString() + " s";
        if (results == null)
          return;
        if (results.States.Count == 0)
        {
          this.listBoxResults.Items.Add((object) "<Empty Results>");
        }
        else
        {
          foreach (TxCollisionState state in results.States)
          {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(this.GetCollisionState(state.Type));
            stringBuilder.Append(" (");
            if (state.FirstObject != null)
              stringBuilder.Append(state.FirstObject.Name);
            stringBuilder.Append(" <-> ");
            if (state.SecondObject != null)
              stringBuilder.Append(state.SecondObject.Name);
            stringBuilder.Append(")");
            stringBuilder.Append(" distance: ");
            stringBuilder.Append(state.Distance);
            if (TxVector.op_Inequality(state.ClosestPointOnFirstObject, (TxVector) null) && TxVector.op_Inequality(state.ClosestPointOnSeocndObject, (TxVector) null))
            {
              stringBuilder.Append(" points: (");
              stringBuilder.Append(state.ClosestPointOnFirstObject.X);
              stringBuilder.Append("; ");
              stringBuilder.Append(state.ClosestPointOnFirstObject.Y);
              stringBuilder.Append("; ");
              stringBuilder.Append(state.ClosestPointOnFirstObject.Z);
              stringBuilder.Append(") <-> (");
              stringBuilder.Append(state.ClosestPointOnSeocndObject.X);
              stringBuilder.Append("; ");
              stringBuilder.Append(state.ClosestPointOnSeocndObject.Y);
              stringBuilder.Append("; ");
              stringBuilder.Append(state.ClosestPointOnSeocndObject.Z);
              stringBuilder.Append(")");
            }
            if (((IEnumerable<TxPenetrationRegion>) state.PenetrationRegions).Count<TxPenetrationRegion>() > 0)
            {
              stringBuilder.Append(" penetration: ");
              stringBuilder.Append(((IEnumerable<TxPenetrationRegion>) state.PenetrationRegions).Count<TxPenetrationRegion>());
              stringBuilder.Append(" curve(s)");
            }
            this.listBoxResults.Items.Add((object) stringBuilder.ToString());
            if (state.Type == 5 && state.FirstObject != null && state.FirstObject is ITxDisplayableObject && state.SecondObject != null && state.SecondObject is ITxDisplayableObject)
            {
              this.ColorCollidingObject(state.FirstObject as ITxDisplayableObject);
              this.ColorCollidingObject(state.SecondObject as ITxDisplayableObject);
              TxApplication.RefreshDisplay();
            }
          }
        }
      }

      private void ColorCollidingObject(ITxDisplayableObject displayableObject)
      {
        if (!this.m_objectOriginalColors.ContainsKey(displayableObject))
        {
          TxColor txColor = (TxColor) null;
          try
          {
            txColor = displayableObject.Color;
          }
          catch (TxUnknownErrorException ex)
          {
            this.m_objectToResetColor.Add(displayableObject);
          }
          if (TxColor.op_Inequality(txColor, (TxColor) null))
            this.m_objectOriginalColors[displayableObject] = txColor;
          else
            this.m_objectToResetColor.Add(displayableObject);
        }
        displayableObject.Color = TxColor.TxColorRed;
      }

      private string GetCollisionState(
        TxCollisionState.TxCollisionStateType collisionStateType)
      {
        string collisionState;
        switch ((int) collisionStateType)
        {
          case 0:
            collisionState = "[Unchecked]";
            break;
          case 1:
            collisionState = "[Separate]";
            break;
          case 2:
            collisionState = "[Near Miss]";
            break;
          case 3:
            collisionState = "[Contact]";
            break;
          case 5:
            collisionState = "[Collision]";
            break;
          default:
            collisionState = "[UNKNOWN]";
            break;
        }
        return collisionState;
      }

      private TxCollisionQueryParams CreateCollisionQueryParams()
      {
        return new TxCollisionQueryParams()
        {
          NearMissDistance = this.NearMissDistance,
          AllowedPenetration = this.AllowedPenetration,
          UseNearMiss = this.MustUseNearMiss,
          ComputeDistanceIfInNearMiss = this.MustComputeDistanceIfInNearMiss,
          FindPenetrationRegions = this.MustFindPenetrationRegions,
          Mode = this.IsCollisionQueryDefinedPair ? (TxCollisionQueryParams.TxCollisionQueryMode) 0 : (TxCollisionQueryParams.TxCollisionQueryMode) 1,
          ReportLevel = this.IsEntityReportLevel ? (TxCollisionQueryParams.TxCollisionReportLevel) 0 : (TxCollisionQueryParams.TxCollisionReportLevel) 1,
          StopQueryAfterFirstCollision = this.MustStopQueryAfterFirstCollision,
          UseAllowedPenetration = this.DoesUseAllowedPenetration,
          UsePredefinedAllowedPairs = this.DoesUsePredefinedAllowedPairs
        };
      }

      private void firstObjectsWindowsFormHost_GotFocus(object sender, RoutedEventArgs e)
      {
        this.m_firstObjectList.Focus();
      }

      private void firstObjectsWindowsFormHost_LostFocus(object sender, RoutedEventArgs e)
      {
      }

      private void secondObjectsWindowsFormHost_GotFocus(object sender, RoutedEventArgs e)
      {
        this.m_secondObjectList.Focus();
      }

      private void secondObjectsWindowsFormHost_LostFocus(object sender, RoutedEventArgs e)
      {
      }

      private void ResetObjectColors()
      {
        foreach (KeyValuePair<ITxDisplayableObject, TxColor> objectOriginalColor in this.m_objectOriginalColors)
          objectOriginalColor.Key.Color = objectOriginalColor.Value;
        this.m_objectOriginalColors.Clear();
        foreach (ITxDisplayableObject displayableObject in this.m_objectToResetColor)
          displayableObject.RestoreColor();
        this.m_objectToResetColor.Clear();
        TxApplication.RefreshDisplay();
      }

      [DebuggerNonUserCode]
      [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
      public void InitializeComponent()
      {
        if (this._contentLoaded)
          return;
        this._contentLoaded = true;
        System.Windows.Application.LoadComponent((object) this, new Uri("/DnProcessSimulateCommands;component/collisions/cuicollisionswindow.xaml", UriKind.Relative));
      }

      [DebuggerNonUserCode]
      [GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
      [EditorBrowsable(EditorBrowsableState.Never)]
      void IComponentConnector.Connect(int connectionId, object target)
      {
        switch (connectionId)
        {
          case 1:
            ((Window) target).Closing += new CancelEventHandler(this.TxWindow_Closing);
            break;
          case 2:
            this.firstObjectsWindowsFormHost = (WindowsFormsHost) target;
            this.firstObjectsWindowsFormHost.GotFocus += new RoutedEventHandler(this.firstObjectsWindowsFormHost_GotFocus);
            this.firstObjectsWindowsFormHost.LostFocus += new RoutedEventHandler(this.firstObjectsWindowsFormHost_LostFocus);
            break;
          case 3:
            this.secondObjectsWindowsFormHost = (WindowsFormsHost) target;
            this.secondObjectsWindowsFormHost.GotFocus += new RoutedEventHandler(this.secondObjectsWindowsFormHost_GotFocus);
            this.secondObjectsWindowsFormHost.LostFocus += new RoutedEventHandler(this.secondObjectsWindowsFormHost_LostFocus);
            break;
          case 4:
            this.listBoxResults = (System.Windows.Controls.ListBox) target;
            break;
          case 5:
            this.timeTextBlock = (TextBlock) target;
            break;
          case 6:
            ((System.Windows.Controls.Primitives.ButtonBase) target).Click += new RoutedEventHandler(this.ComputeTestButton_Click);
            break;
          default:
            this._contentLoaded = true;
            break;
        }
      }
    }
}
